# encoding: utf-8
class DataobjectsController < ApplicationController
  before_filter :authenticate_user!, :only => [:new]
  before_filter :get_project
  before_filter :is_member_of_project?

  MAX_FILE_SIZE = 3145728   # 3 MegaBytes
  ALLOWED_MIME_TYPES = ["image/png", "image/gif", "image/jpeg", "application/pdf", "application/zip", "text/plain" ]
  FILE_UPLOAD_DIRECTORY = "#{Rails.root.to_s}/file_upload/"

  def index   
    if params[:project_id]
      @dataobjects = @project.dataobjects.where(:project_id => params[:project_id], :bug_id => nil)
    end
    respond_to do |format|
      format.html # index.html.erb
    end
  end
  
  def download
    @dataobject = Dataobject.find(params[:id])
    if !File.exist?(@dataobject.path)
      flash[:error] = t :no_file_exists, :scope => [:flash, :error]
      respond_to do |format|
        if params[:bug_id]
          format.html { redirect_to(project_bug_path(params[:project_id], params[:bug_id])) }
        elsif params[:project_id]
          format.html { redirect_to(project_dataobjects_path(params[:project_id])) }
        end
      end
    else
      send_file(@dataobject.path, :filename => @dataobject.name)
    end
  end

  def new
    if params[:bug_id]
      @bug = Bug.where(:id => params[:bug_id])
    end
    @dataobject = Dataobject.new
    respond_to do |format|
      format.html # new.html.erb
    end
  end

  def edit    
    @dataobject = Dataobject.find(params[:id])
  end

  def upload
	
	# Check if directory exists
	if !File.exists?(FILE_UPLOAD_DIRECTORY) || !File.directory?(FILE_UPLOAD_DIRECTORY)
	# If file exists but is not a directory, delete file
		if File.exists?(FILE_UPLOAD_DIRECTORY)
			File.delete(FILE_UPLOAD_DIRECTORY)
		end
		# Create File upload directory
		Dir.mkdir(FILE_UPLOAD_DIRECTORY)
	end

    @upload = params[:upload]
    @error_occurred = false

    #ensure valid file is being uploaded
    if !@upload
      # there was no file selected for upload in the view
      flash[:error] = t :no_file_chosen, :scope => [:flash, :error]
      @error_occurred = true
    elsif !ALLOWED_MIME_TYPES.index(@upload['datafile'].content_type)
      flash[:error] = t :invalid_mime_type, :scope => [:flash, :error]
      @error_occurred = true
    elsif @upload['datafile'].size > MAX_FILE_SIZE
      # the file is largar than 3 MegaBytes
      flash[:error] = t :file_too_large, :scope => [:flash, :error]
      @error_occurred = true
    end
    
  if @error_occurred
    #redirect to prior page
    respond_to do |format|
      if params[:bug_id]
        format.html { redirect_to(project_bug_path(params[:project_id], params[:bug_id])) }
      elsif params[:project_id]
        format.html { redirect_to(project_dataobjects_path(params[:project_id])) }
      end
    end
  else
    # there was a proper file selected by the user
    # start operating on that file
    @dataobject = Dataobject.new(params[:dataobject])
    @name = @upload['datafile'].original_filename
    @directory = FILE_UPLOAD_DIRECTORY + @project.name

    # transform filename for proper identification on the filesystem
    # and store it in the dataobject instance's path field
    @fs_identifier = Time.new.to_i.to_s
    if params[:bug_id]
      @fs_identifier = @fs_identifier + "_bug" + params[:bug_id]
    end
    @fs_identifier = @fs_identifier + "_" + @name
      
    @path = File.join(@directory, @fs_identifier)

    # fill dataobject instance with data
    @dataobject.name = @name
    @dataobject.bug_id = params[:bug_id]
    @dataobject.project_id = params[:project_id]
    @dataobject.description = params[:description]
    @dataobject.path = @path

    # open a transaction to ensure atomicity of database and filesystem
    # operations
    ActiveRecord::Base.transaction do
      # ensure directory for current project has already been created
      if !File.exists?(@directory) || !File.directory?(@directory)
		# If file exists but is not a directory delete file before creating the directory
		if File.exists?(@directory)
			File.delete(@directory)
		end
        Dir.mkdir(@directory)
      end
      File.open(@path, "wb") { |f| f.write(@upload['datafile'].read) }
      respond_to do |format|
        if @dataobject.save
          if params[:bug_id]
            flash[:notice] = t :file_upload_success, :scope => [:flash, :notice]
            format.html { redirect_to(project_bug_path(params[:project_id], params[:bug_id])) }
          elsif params[:project_id]
            flash[:notice] = t :file_upload_success, :scope => [:flash, :notice]
            format.html { redirect_to(project_dataobjects_path(params[:project_id])) }
          end
        else
          format.html { render :action => "new" }
        end
      end
    end
  end
end

def destroy
  if params[:id]
    @dataobject = Dataobject.find(params[:id])
  end
  if !File.exist?(@dataobject.path)
    flash[:error] = t :no_file_exists, :scope => [:flash, :error]
  else
    ActiveRecord::Base.transaction do
      File.delete(@dataobject.path)
      @dataobject.destroy
      flash[:notice] = t :file_delete_success, :scope => [:flash, :notice]
    end
  end
  respond_to do |format|
    if params[:bug_id] && params[:id]
      format.html { redirect_to(project_bug_path(params[:project_id], params[:bug_id])) }
    elsif params[:id]
      format.html { redirect_to(project_dataobjects_path(params[:project_id])) }
    end
  end
end
  
end # end of class

